﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using Evolution.Client.ImportData.Infrastructure;
using Evolution.Client.ImportData.Mapper;

namespace Evolution.Client.ImportData.Actions
{
    public class GenerateDataObjectTemplateProcess
    {
        /// <summary>
        /// Generate data object structure to XML file
        /// </summary>
        public void DoWork()
        {
            Console.WriteLine("\nBEGIN: Generate data object structure to XML file\n");
            var dataObjectsMapping = ImportDataMapper.GetDataObjectsMapping();

            foreach (DataObjectMapping dataObject in dataObjectsMapping)
            {
                Console.WriteLine("Serializing Data Object:[{0}]", dataObject.Name);
                Console.WriteLine("ClassType: {0}, FilePath: {1}", dataObject.ClassType, dataObject.FilePath);

                var objectType = Type.GetType(dataObject.ClassType);
                if(objectType != null)
                {
                    try
                    {
                        object dataInstance = ImportDataMapper.InitializeDeepHierachyObject(objectType);
                        SerializeDataObject(dataInstance.GetType(), dataInstance, dataObject.FilePath);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                    }
                }
                else
                {
                    Console.WriteLine("ERROR: Cannot find this type. May be missing reference assembly!");
                }
            }
            Console.WriteLine("\nEND: Generate data object structure to XML file");
        }
        
        
        /// <summary>
        /// Serialize data object and write to XML file
        /// </summary>
        /// <param name="objectType"></param>
        /// <param name="dataInstance"></param>
        /// <param name="fileName"></param>
        public void SerializeDataObject(Type objectType, object dataInstance, string fileName)
        {
            var listObjects = ImportDataMapper.GetList(objectType);
            listObjects.Add(dataInstance);

            var folderPath = string.Format(@"{0}", ImportSettings.GetInstance().TemplateFolder);
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);

            var settings = new XmlWriterSettings { Indent = true };
            using (var writer = XmlWriter.Create(string.Format(@"{0}\{1}", folderPath, fileName), settings))
            {
                DataContractSerializer serializer = new DataContractSerializer(listObjects.GetType());
                serializer.WriteObject(writer, listObjects);
            }
        }
    }
}